import { defineStore } from "pinia";
import dictApi from "@/api/system/dict.js"


const dictStore = defineStore("dict store",
    {
        state: () => ({
            cache: [{}] // classCode:xxxx-xxxx  data:[{key:value}]  expirTime: ; 
        }),

        actions: {
            getStatusDict(){
                return new Promise((resolve, reject) => {
                    dictApi.getDataByCode("System:Status").then(res => {
                        this.cache.push({});
                        resolve(res);
                    }).catch(error => { reject(error); });

                });
            },
            getDictdata(classCode) {
                return new Promise((resolve, reject) => {
                    dictApi.getDataByCode(classCode).then(res => {
                        this.cache.push({});
                        resolve(res);
                    }).catch(error => { reject(error); });

                });
            },
            async getDictDataCache(classCode) {

                let retData = {};
                let cachedata = this.cache.map(x => x.classCode == classCode);
                if (cachedata && cachedata.expirTime > Date.now()) {
                    retData = cachedata.data;
                }
                else {
                    var res = await dictApi.getDataByCode(classCode);
                    if (res && res.data && res.data.data) {
                        retData = res.data.data
                        this.cache.push({ classCode: classCode, data: res.data.data, expirTime: Date.now() + 30 * 60 * 1000 });
                    }
                }
                return retData;
            }

        }
    }
);


export default dictStore;